package com.weijing.pretty_app.fragment

import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import androidx.fragment.app.Fragment
import com.weijing.pretty_app.R
import com.weijing.pretty_app.databinding.FragmentPasswordBinding
import com.weijing.pretty_app.util.KeyUtil
import com.weijing.pretty_app.util.SPUtil
import com.weijing.pretty_app.util.ToastUtils

/**
 * 修改密码页面
 */
class PasswordFragment : Fragment() {

    private lateinit var binding: FragmentPasswordBinding

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentPasswordBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        binding.passwordTvSave.setOnClickListener {
            val admin = binding.passwordEtAdmin.text.toString().trim()
            val pwd1 = binding.passwordEtNew1.text.toString().trim()
            val pwd2 = binding.passwordEtNew2.text.toString().trim()

            if (admin.isEmpty()) {
                ToastUtils.show(getString(R.string.Admin_password) + " " + getString(R.string.cannot_empty))
                return@setOnClickListener
            }
            if (admin != "12345678") {
                ToastUtils.show(getString(R.string.Admin_password) + " Error!")
                return@setOnClickListener
            }
            if (pwd1.isEmpty()) {
                ToastUtils.show(getString(R.string.New_password) + " " + getString(R.string.cannot_empty))
                return@setOnClickListener
            }

            if (pwd2.isEmpty()) {
                ToastUtils.show(getString(R.string.Confirm_new_password) + " " + getString(R.string.cannot_empty))
                return@setOnClickListener
            }

            if (pwd2 != pwd1) {
                ToastUtils.show(getString(R.string.pwd_confim_error))
                return@setOnClickListener
            }

            SPUtil.put(KeyUtil.LOGIN_PWD, pwd2)
            ToastUtils.showLong(getString(R.string.Modified_successfully))
        }

        setupCustomKeyboard(
            listOf(
                binding.passwordEtAdmin, binding.passwordEtNew1, binding.passwordEtNew2
            ),
            mapOf(
                "0" to binding.passwordTv0, "1" to binding.passwordTv1, "2" to binding.passwordTv2,
                "3" to binding.passwordTv3, "4" to binding.passwordTv4, "5" to binding.passwordTv5,
                "6" to binding.passwordTv6, "7" to binding.passwordTv7, "8" to binding.passwordTv8,
                "9" to binding.passwordTv9, "." to binding.passwordTvGot
            ),
            binding.passwordTvDelete, binding.passwordTvESC
        )
    }

    private fun setupCustomKeyboard(
        editTexts: List<EditText>,
        keyMap: Map<String, View>, // "1" to button1, "." to buttonDot 等
        deleteButton: View,
        clearButton: View,
    ) {
        var currentEditText: EditText? = null

        // 禁用系统软键盘并记录当前焦点 EditText
        editTexts.forEach { editText ->
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                editText.showSoftInputOnFocus = false
            } else {
                try {
                    val method = EditText::class.java.getMethod(
                        "setShowSoftInputOnFocus", Boolean::class.javaPrimitiveType
                    )
                    method.isAccessible = true
                    method.invoke(editText, false)
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }

            editText.setOnFocusChangeListener { _, hasFocus ->
                if (hasFocus) currentEditText = editText
            }
        }

        // 为每个按钮设置对应字符
        keyMap.forEach { (value, button) ->
            button.setOnClickListener {
                currentEditText?.apply {
                    val start = selectionStart
                    val end = selectionEnd
                    val newText = text.replaceRange(start, end, value)
                    setText(newText)
                    setSelection(start + value.length)
                }
            }
        }

        // 删除按钮点击
        deleteButton.setOnClickListener {
            currentEditText?.apply {
                val start = selectionStart
                val end = selectionEnd
                if (start != end) {
                    text.replace(start, end, "")
                    setSelection(start)
                } else if (start > 0) {
                    text.delete(start - 1, start)
                    setSelection(start - 1)
                }
            }
        }

        // 清空按钮点击
        clearButton.setOnClickListener {
            currentEditText?.apply {
                setText("")
            }
        }
    }
}